/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.gadgets.bookmarks.server;

import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import com.gadglet.core.BizletRequestHandler;
import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.core.GadgletResponse;
import com.gadglet.core.GadgletResponse.ContentRecord;
import com.gadglet.core.RequestException;
import com.gadglet.data.DomainUser;
import com.gadglet.data.DomainUserUtils;
import com.gadglet.data.SharedItemReff;
import com.gadglet.data.utils.ContentItemHelper;
import com.gadglet.data.utils.HasMoreItems;
import com.gadglet.gadgets.bookmarks.shared.Params;
import com.gadglet.params.FieldErrorTypes;
import com.gadglet.params.GadgetViewState;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.ReqErrorTypes;
import com.gadglet.params.SharingType;

public class RequestHandler extends BizletRequestHandler {
	Logger log = Logger.getLogger(this.getClass().getName());

	private final ContentItemHelper helper = new ContentItemHelper();

	
	/**
	 * Delete Personal note
	 * */
	@Override
	public void doDelete(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {
		helper.delete(request, BookMarksList.class);
	}

	/**
	 * Share Personal note with a friend
	 * */
	@Override
	public void doShare(GadgletRequestWrapper request, GadgletResponse res)
			throws RequestException {

		helper.shareItem(request, BookMarksList.class);
	}


	/**
	 * Return a list of Domain user friends and their sharing definition for a given personal
	 * note item
	 * */
	@Override
	public void doSharedList(GadgletRequestWrapper request, GadgletResponse res)
			throws RequestException {

		BookMarksList item = (BookMarksList) helper
				.getSingleItemByKey(request, BookMarksList.class);

		if (!item.isOwnedByMe(request))
			throw new RequestException(ReqErrorTypes.UNAUTHORIZED_OPERATION);

		item.getDomainFriendsSharing(request, res);

	}

	@Override
	public void doAdd(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {

		String url = request.getParameter(Params.BOOKMARK_URL.getParamName());
		if (url == null || url.isEmpty()) {
			response.addFieldError(Params.BOOKMARK_URL.getParamName(),
					FieldErrorTypes.FIELD_IS_EMPTY);
			throw new RequestException(ReqErrorTypes.MISSING_ARGUMENT);
		}
		// String field is limited to 500 chars...
		if (url.length() > 499)
			throw new RequestException(ReqErrorTypes.CONTENT_EXCEED_MAX_LENGTH);

		
		String title = request.getParameter(Params.BOOKMARK_TITLE.getParamName());
		if (title == null || title.isEmpty()) {
			response.addFieldError(Params.BOOKMARK_TITLE.getParamName(),
					FieldErrorTypes.FIELD_IS_EMPTY);
			throw new RequestException(ReqErrorTypes.MISSING_ARGUMENT);
		}
		
		if (title.length() > 499)
			throw new RequestException(ReqErrorTypes.CONTENT_EXCEED_MAX_LENGTH);
		

		BookMarksList item = new BookMarksList(url,title,null, request);

		helper.saveNew(item);
	}

	
	
	@Override
	public void doUpdate(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {
		// check imput
		String url = request.getParameter(Params.BOOKMARK_URL.getParamName());

		if (url == null || url.isEmpty()) {
			response.addFieldError(Params.BOOKMARK_URL.getParamName(),
					FieldErrorTypes.FIELD_IS_EMPTY);

			throw new RequestException(ReqErrorTypes.MISSING_ARGUMENT);
		}
		
		
		String title = request.getParameter(Params.BOOKMARK_TITLE.getParamName());

		if (title == null || title.isEmpty()) {
			response.addFieldError(Params.BOOKMARK_TITLE.getParamName(),
					FieldErrorTypes.FIELD_IS_EMPTY);

			throw new RequestException(ReqErrorTypes.MISSING_ARGUMENT);
		}
		
		BookMarksList item = (BookMarksList) helper
				.getSingleItemByKey(request, BookMarksList.class);
		
		item.setBookMarkTitle(title);
		item.setBookMarkUrl(url);
			
		helper.updated(null, item, request);
	}

	/**
	 * Return a list of bookmarks
	 * */
	@Override
	public void doView(GadgletRequestWrapper request, GadgletResponse response)
			throws RequestException {

		HasMoreItems hasMore = new HasMoreItems();
		int returnedItems;
		HashMap<String, Object> params = null;
		
			
		List<BookMarksList> items = (List<BookMarksList>) helper
				.getSharedItems(request, BookMarksList.class,
						request.getFilterBy(),
						request.getFilterByDeclaration(), params,
						request.getOrderBy(), request.getStartFrom(),
						request.getItemNum(), hasMore);


		returnedItems = items.size();
		if (hasMore.isTrue()) {
			response.setHasMore(true);
			returnedItems = returnedItems - 1;
		} else
			response.setHasMore(false);

		response.setAddPermit(true);

		response.setTotalItemsNum(returnedItems);

		int count = 0;
		for (BookMarksList item : items) {
			// exit in the last item
			if (count++ == returnedItems)
				break;
			String title = null;

			if (!request.getGadgetViewState().equals(GadgetViewState.CANVAS)
					&& item.getBookMarkTitle().length() > 40)
				title = item.getBookMarkTitle().substring(0, 40) + "...";
			else
				title = item.getBookMarkTitle();

			ContentRecord record = response.newItem();

			record.addItemKeyField(item.getContentItemKey());
			record.addItemField(Params.BOOKMARK_TITLE.getParamName(), title);
			record.addItemField(Params.BOOKMARK_URL.getParamName(), item.getBookMarkUrl());
			record.addItemField(Params.BOOKMARK_TYPE.getParamName(), 
					item.getBookMarkType().toString());

			List<SharedItemReff> shares = item.getSharedItemReff();
			boolean isOwner = false;
			boolean isEditor = false;

			if (shares != null) {

				for (SharedItemReff share : shares) {
					if (share.getSharedWithId().equals(
							request.getCurrentUserId())
							&& share.getSharingType().equals(SharingType.OWNER)) {
						isOwner = true;
						isEditor = true;
					}

					if (share.getSharedWithId().equals(
							request.getCurrentUserId())
							&& share.getSharingType().equals(SharingType.EDIT))
						isEditor = true;
				}

				record.setGadgetPermissions(isEditor, isOwner, isOwner);

				if (!isOwner) {
					// send info about the owner need to change !!!!
					DomainUser owner = DomainUserUtils.getDomainUserByUniqueId(
							item.getOwnerId(), request.getCurrentDomainUser()
									.getAccount());

					record.addItemField(
							ProfileFields.PROFILE_NICKNAME.getParamName(),
							owner.getNickName());
					record.addItemField(
							ProfileFields.PROFILE_TITLE.getParamName(),
							owner.getTitle());

					if (owner.getPhotoUrl() != null
							&& owner.getPhotoUrl().length() > 0)
						record.addItemField(ProfileFields.PROFILE_THUMBNAILURL
								.getParamName(), owner.getPhotoUrl());

				}
			}

		}

	}

}
